package service

import (
	"chat/common"
	utils "chat/util"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

type UserMusic struct {
	common.AllCommonStruct
	MusicName string `binding:"required" gorm:"notnull;size:100;comment:音乐名称" json:"musicName"`
	MusicUrl  string `binding:"required" gorm:"notnull;size:500;comment:音乐url" json:"musicUrl"`
	UserId    int    `binding:"required" gorm:"comment:用户ID" json:"userId"`
}
type UserId struct {
	UserId int `binding:"required" json:"userId"`
}
type MusicId struct {
	UserId int `binding:"required" json:"userId"`
	Id     int `binding:"required" json:"id"`
}

func (m *UserMusic) TableName() string {
	return "music_list"
}
func (m *UserMusic) GetMusicList(ctx *gin.Context, db *gorm.DB) {
	var u UserId
	var musicList []UserMusic
	if bindErr := ctx.ShouldBindJSON(&u); bindErr != nil {
		utils.Result(http.StatusBadRequest, nil, ctx)
		return
	}
	_ = db.Table(m.TableName()).Where("user_id = ? AND status_cd = 1", u.UserId).Order("id desc").Find(&musicList)
	utils.Result(http.StatusOK, musicList, ctx)

}
func (m *UserMusic) UploadMusic(ctx *gin.Context, db *gorm.DB) {
	var u, ok = ctx.GetQuery("userId")
	if !ok {
		utils.Result(http.StatusBadRequest, nil, ctx)
		return
	}
	form, err := ctx.MultipartForm()
	if err != nil {
		utils.Result(http.StatusBadRequest, err.Error(), ctx)
		return
	}
	var userId, _ = strconv.Atoi(u)
	files := form.File["files"]
	var MusicArr []*UserMusic
	for _, v := range files {
		fmt.Println(v.Header, v.Filename)
		if !strings.HasPrefix(v.Header.Get("Content-Type"), "audio") {
			continue
		}
		unix := time.Now().Unix()
		basePath := fmt.Sprintf("%s/%s-%s", "static", strconv.Itoa(int(unix)), filepath.Base(v.Filename))
		err := ctx.SaveUploadedFile(v, basePath)
		if err != nil {
			return
		}
		getwd, err := os.Getwd()
		if err != nil {
			return
		}
		v.Filename = strings.TrimSpace(v.Filename)
		var now = time.Now().Format("2006-01-02")
		key := now + "/" + filepath.Base(v.Filename)
		if common.QiniuUploader(path.Join(getwd, "/", basePath), key) {
			music := &UserMusic{
				AllCommonStruct: common.AllCommonStruct{},
				MusicName:       v.Filename,
				MusicUrl:        fmt.Sprintf("%s/%s", common.BASEURL, key),
				UserId:          userId,
			}
			MusicArr = append(MusicArr, music)
		}
	}
	rows := db.Table(m.TableName()).Create(MusicArr)
	if rows.RowsAffected > 0 {
		utils.Result(http.StatusOK, nil, ctx)
	} else {
		utils.Result(http.StatusBadRequest, nil, ctx)
	}

}
func (m *UserMusic) DeleteMusic(ctx *gin.Context, db *gorm.DB) {
	var music MusicId
	if bindErr := ctx.ShouldBindJSON(&music); bindErr != nil {
		utils.Result(http.StatusBadRequest, nil, ctx)
		return
	}
	rows := db.Table(m.TableName()).Where("id=?AND user_id=?", music.Id, music.UserId)
	if rows.RowsAffected > 0 {
		utils.Result(http.StatusOK, nil, ctx)
	} else {
		utils.Result(http.StatusBadRequest, nil, ctx)
	}
}
func (m *UserMusic) RandomMusic(ctx *gin.Context, db *gorm.DB) {
	var music []UserMusic
	rows := db.Table(m.TableName()).Order("RAND()").Limit(1).Find(&music)
	if rows.RowsAffected > 0 {
		utils.Result(http.StatusOK, music, ctx)
	} else {
		utils.Result(http.StatusOK, music, ctx)
	}
}
